
package com.leetcode.stack;

import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Solution496
 */
public class Solution496 {

    public static void main(String[] args) {
        Solution496 s = new Solution496();
        int[] nums1 = { 1, 3, 5, 2, 4 };
        int[] nums2 = { 6, 5, 4, 3, 2, 1, 7 };
        int[] array = s.nextGreaterElement(nums1, nums2);
        Arrays.stream(array).forEach(System.out::println);
    }

    public int[] nextGreaterElement(int[] nums1, int[] nums2) {

        Deque<Integer> stack = new LinkedList<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums2.length; ++i) {
            while (!stack.isEmpty() && nums2[i] > stack.peek()) {
                map.put(stack.pop(), nums2[i]);
            }
            stack.push(nums2[i]);
        }

        return Arrays.stream(nums1).map(e -> map.getOrDefault(e, -1)).toArray();

    }
}